<template>
	<div class="edit-popup">
		<popup ref="popupRef" title="添加产品" :async="true" width="1200px" @confirm="handleSubmit" @close="handleClose">
			<el-card class="!border-none" shadow="never">
			  <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
			    <el-form-item label="产品分类">
			      <el-select class="w-[200px]" v-model="queryParams.cate_id" placeholder="请选择" clearable filterable >
			        <el-option v-for="item in productCateList" :key="item.id" :label="item.name" :value="item.id" />
			      </el-select>
			    </el-form-item> 
			    <!-- <el-form-item label="准入区域">
			      <el-input class="w-[200px]" v-model="queryParams.name" clearable />
			    </el-form-item> -->
				 <el-form-item label="产品名称">
				   <el-input class="w-[200px]" v-model="queryParams.name" clearable />
				 </el-form-item>
			    <el-form-item>
			      <el-button type="primary" @click="getDetail">查询</el-button>
			    </el-form-item>
			  </el-form>
			</el-card>
			<el-table ref="multipleTable" :data="channelList" v-loading="loading" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
			    <el-table-column type="selection" width="55"></el-table-column>
				<el-table-column label="产品分类" prop="cate_name" min-width="160" />
				<el-table-column label="银行" prop="bank_name" min-width="160" /> 
				<el-table-column label="产品名称" prop="name" min-width="160" /> 
				<el-table-column label="产品logo" min-width="160">
				  <template #default="{ row }">
				    <image-contain v-if="row.logo" :src="row.logo" :width="60" :height="45" :preview-src-list="[row.logo]" preview-teleported fit="contain" />
				  </template>
				</el-table-column>
				<el-table-column label="最高额度(万)" prop="quota" min-width="160" show-tooltip-when-overflow/> 
				<el-table-column label="授信年限" min-width="160">
				  <template #default="{ row }">
				    <template v-for="(item, index) in row.credit_year" :key="index"> {{ item }}年/ </template>
				  </template>
				</el-table-column> 
				<el-table-column label="利率类型" min-width="160">
				  <template #default="{ row }"> {{ row.rate_type == 1 ? '年化利率' : '日化利率' }} </template>
				</el-table-column> 
				<el-table-column label="利率值" min-width="160">
				  <template #default="{ row }">
				    {{ row.rate_type == 1 ? ((parseInt(row.rate_start * 10000)/100).toString() + '%') : ((parseInt(row.rate_start * 100000)/100).toString() + '‰') }}
				    -
				    {{ row.rate_type == 1 ? (parseInt(row.rate_end * 10000)/100).toString() + '%' : (parseInt(row.rate_end * 100000)/100).toString() + '‰' }}
				  </template>
				</el-table-column> 
				<el-table-column label="还款方式" min-width="160">
				  <template #default="{ row }"> {{ localGetRepaymentTypeText(row.repayment_type) }} </template>
				</el-table-column> 
				<el-table-column label="准入区域" min-width="160">
				  <template #default="{ row }"> {{ localGetAccessAreasText(row.access_area_arr) }} </template>
				</el-table-column> 
			</el-table>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type { FormInstance } from 'element-plus'
	import { productLists, productCate } from '@/api/product/product';
	import Popup from '@/components/popup/index.vue'
	import { getModulesKey } from '@/router'
	import {isEmpty} from "@/utils/util";
	const channelList = ref([])
	const loading = ref(false)
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		console.log(val);
		multipleSelection.value = val;
	}
	let multipleTable:any;
	nextTick(()=>{
		multipleTable = ref();
	})
	const toggleSelection = (rows:any)=> {
		if (rows) {
			rows.forEach((row:any,index:number) => {
				// console.log(234,multipleTable);
				// this.$refs.multipleTable.toggleRowSelection(row);
				// multipleTable.value.toggleRowSelection(row)
				multipleTable.value.toggleRowSelection(rows[index]);
			});
		} else {
			// this.$refs.multipleTable.clearSelection();
			// multipleTable.value.clearSelection()
		}
	}
	const setFormData = async(data : Record<any, any>) => {
		console.log(data);
		multipleSelection.value = data.pid;
		getDetail();
		const lists  = await productCate({});
		productCateList.value = lists || [];
	}
	const productCateList = ref([])
	const queryParams = reactive({
		cate_id: null,
		name: '',
		// account: ''
	})
	const getDetail = async () => {
		loading.value = true;
		const data = await productLists({
			page_no: 1,
			page_size: 9999,
			cate_id: queryParams.cate_id,
			name: queryParams.name,
			// account: queryParams.account
		})
		channelList.value=data.lists || [];
		loading.value = false;
		// await nextTick()
		// toggleSelection(multipleSelection);
	}
	const handleSubmit = async () => {
		// mode.value == 'edit' ? await productCateEdit(newFormData) : await productCateAdd(newFormData)
		popupRef.value?.close()
		emit('success',multipleSelection.value)
	}
	
	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')

	const componentsOptions = ref(getModulesKey())
	const querySearch = (queryString : string, cb : any) => {
		const results = queryString
			? componentsOptions.value.filter((item) =>
				item.toLowerCase().includes(queryString.toLowerCase())
			)
			: componentsOptions.value
		cb(results.map((item) => ({ value: item })))
	}
	const formData = reactive({
		id: '',
		//名称
		name: '',
		//业务流程
		business_stage: [],
		//备注
		remark: '',
		//启用状态
		is_enable: 1
	})

	const formRules = {
		name: [
			{
				required: true,
				message: '请输入分类名称',
				trigger: 'blur'
			}
		],
		business_stage: [
			{
				required: true,
				message: '请编辑业务流程',
				trigger: 'blur'
			}
		],
		component: [
			{
				required: true,
				message: '请选择启用状态',
				trigger: 'blur'
			}
		]
	}
	const menuOptions = ref<any[]>([])

	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}
	
	const addBusinessStage = () => {
		formData.business_stage.push({name:''});
	}
	
	const deleteBusinessStage = (i:any) => {
		formData.business_stage.splice(i,1);
	}

	const handleClose = () => {
		emit('close')
	}
	
	const localGetRepaymentTypeText = (repaymentTypes: number[]| null): string => {
	  //1.先息后本 2.等额本息 3.等额本金
	  let repaymentTypeStr = ''
	  if (!isEmpty(repaymentTypes)) {
	    (repaymentTypes as number[]).forEach((item,index )  => {
	      if (item == 1) {
	        repaymentTypeStr += '先息后本/'
	      } else if (item == 2) {
	        repaymentTypeStr += '等额本息/'
	      } else if (item == 3) {
	        repaymentTypeStr += '等额本金/'
	      } else if (item == 4) {
	        repaymentTypeStr += '一次性还本付息/'
	      } else if (item == 5) {
	        repaymentTypeStr += '随借随还/'
	      }
	
	    })
	  }
	  return repaymentTypeStr.slice(0, -1)
	}
	
	
	const localGetAccessAreasText = (accessAreaArr: Array<any>): string => {
	  let accessAreaText = ''
	  accessAreaArr.forEach((item, index) => {
	    accessAreaText += (item?.Name)+'/'
	  })
	  return accessAreaText.replace(/[\\//]$/, "");
	}

	defineExpose({
		open,
		setFormData,
		getDetail
	})
</script>